const {appID,appsecret}=require('../config');
const rp=require('request-promise-native')
const {writeFile,readFile}=require('fs')
const menu=require('./menu')
class Wechat {
  constructor(){}
  getAccessToken(){
    const url=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`
    return new Promise((resolve,reject)=>{
      rp({method:'GET',url:url,json:true}).then(res=>{
        console.log(res)
        //{"access_token":"ACCESS_TOKEN","expires_in":7200} 2*60*60  5*60
        res.expires_in=Date.now()+(res.expires_in-300)*1000
        resolve(res)
      }).catch(err=>{
        console.log(err)
        reject('getAccessToken问题：'+err)
      })
    })
  }

  saveAccessToken(accessToken){
    accessToken=JSON.stringify(accessToken)
    return new Promise((resolve,reject)=>{
      writeFile('./accessToken.txt',accessToken,err=>{
        if(!err){
          resolve()
        }else{
          reject()
        }
      })
    })
  }
  readAccessToken(){
    return new Promise((resolve,reject)=>{
      readFile('./accessToken.txt',(err,data)=>{
        if(!err){
          data=JSON.parse(data)
          resolve(data)
        }else{
          reject(err)
        }
      })
    })
  }

  isValidAccessToken(data){
    if(!data&&!data.access_token&&!data.expires_in){
      return false
    }
    return data.expires_in>Date.now() //true 没有过期 false 过期
  }
  fetchAccessToken(){
    if(this.access_token&&this.expire_in&&this.isValidAccessToken(this)){
      //之前保存过且有效
      return Promise.resolve({
        access_token:this.access_token,
        expire_in:this.expire_in
      })
    }
   return  this.readAccessToken()
        .then(async res => {
          if (this.isValidAccessToken(res)) {
            return Promise.resolve(res)
          } else {
            const res = await this.getAccessToken()
            await this.saveAccessToken(res)
            return Promise.resolve(res)
          }
        })
        .catch(async err => {
          const res = await this.getAccessToken()
          await this.saveAccessToken(res)
          return Promise.resolve(res)
        })
        .then(res=>{
          this.access_token=res.access_token
          this.expire_in=res.expire_in
          return Promise.resolve(res)
        })
  }

  createMenu(){
    return new Promise(async (resolve, reject) => {
      try {
        let data=await this.fetchAccessToken()
        const url=` https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token}`
        const result=await rp({method: 'POST',url,json: true,body:menu})
        resolve(result)
      }catch (e) {
        reject('createMenu出错：'+e)
      }
    })
  }
  deleteMenu(){
    return new Promise(async (resolve, reject) => {
      try {
        let data=await this.fetchAccessToken()
        let url=`https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${data.access_token}`;
        const result=await rp({method:'GET',url,json:true});
        resolve(result);
      }catch (e) {
        reject('deleteMenu报错'+e)
      }
    })
  }
}
(async ()=>{
  const w=new Wechat()
  await w.deleteMenu()
  let result=await w.createMenu(menu)
  console.log(result)
})()


